<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="tenant_id" label="所属商户" required>
        <uni-data-select 
          v-if="isAdmin" 
          v-model="formData.tenant_id" 
          :localdata="tenantOptions" 
          @change="onTenantChange"
          placeholder="请选择商户">
        </uni-data-select>
        <uni-easyinput 
          v-else 
          v-model="formData.tenant_id" 
          disabled>
        </uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="category_id" label="所属分类" required>
        <uni-data-select
          v-model="formData.category_id"
          :localdata="categoryOptions"
          :placeholder="isAdmin && !formData.tenant_id ? '请先选择商户' : '请选择分类'"
          :disabled="isAdmin && !formData.tenant_id">
        </uni-data-select>
        <text v-if="isAdmin && !formData.tenant_id" style="color: #909399; font-size: 12px; margin-top: 5px;">
          请先选择商户，再选择分类
        </text>
      </uni-forms-item>
      <uni-forms-item name="name" label="菜品名称" required>
        <uni-easyinput placeholder="菜品名称" v-model="formData.name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="image" label="菜品图片">
        <!-- 简单的图片上传 -->
        <view v-if="formData.image" style="margin-bottom: 10px;">
          <image 
            :src="formData.image" 
            mode="aspectFill" 
            style="width: 120px; height: 120px; border-radius: 8px;"
          ></image>
        </view>
        
        <uni-file-picker 
          v-model="formData.imageFiles" 
          fileMediatype="image" 
          mode="grid"
          :auto-upload="true"
          :upload-user-oid="true"
          :folder="uploadConfig.folder"
          @select="onImageSelect"
          @success="onUploadSuccess"
          @delete="onImageDelete"
          limit="1">
        </uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="description" label="菜品描述">
        <uni-easyinput placeholder="菜品描述" v-model="formData.description" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="price" label="价格" required>
        <uni-easyinput type="number" placeholder="输入价格" v-model="formData.price">
          <template v-slot:right>
            <text style="color: #666;">元</text>
          </template>
        </uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="original_price" label="原价">
        <uni-easyinput type="number" placeholder="输入原价（可选）" v-model="formData.original_price">
          <template v-slot:right>
            <text style="color: #666;">元</text>
          </template>
        </uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="sort" label="排序值">
        <uni-easyinput placeholder="排序值（越小越靠前）" type="number" v-model="formData.sort"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="is_hot" label="热销标记">
        <switch @change="binddata('is_hot', $event.detail.value)" :checked="formData.is_hot"></switch>
      </uni-forms-item>
      <uni-forms-item name="is_new" label="新品标记">
        <switch @change="binddata('is_new', $event.detail.value)" :checked="formData.is_new"></switch>
      </uni-forms-item>
      <uni-forms-item name="status" label="状态">
        <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/food_items.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'food_items';

  function getValidator(fields) {
    let result = {};
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key];
      }
    }
    return result;
  }

  export default {
    data() {
      let formData = {
        "tenant_id": "",
        "category_id": "",
        "name": "",
        "image": "",
        "description": "",
        "price": null,
        "original_price": null,
        "sort": 100,
        "is_hot": false,
        "is_new": false,
        "status": 1,
        "created_at": null,
        "updated_at": null,
        "imageFiles": []
      };
      
      return {
        formData,
        formDataId: '',
        formOptions: {
          "status_localdata": [
            {
              "text": "下架",
              "value": 0
            },
            {
              "text": "上架",
              "value": 1
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        },
        isAdmin: false,
        currentTenantId: '',
        tenantOptions: [],
        categoryOptions: [],
        allCategories: [],
        originData: null,
        uploadConfig: {
          folder: 'food_images'
        }
      };
    },
    onLoad(e) {
      // 获取用户信息
      const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
      this.isAdmin = userInfo.isAdmin === true;
      this.currentTenantId = userInfo.tenant_id || '';
      
      // 处理编辑ID
      if (e.id) {
        this.formDataId = e.id;
        this.getDetail(e.id);
      }
      
      // 加载商户和分类
      if (this.isAdmin) {
        this.loadTenants();
      } else {
        this.formData.tenant_id = this.currentTenantId;
        this.loadCategories();
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules);
    },
    methods: {
      /**
       * 加载商户数据
       */
      async loadTenants() {
        try {
          const { result } = await uniCloud.callFunction({
            name: 'get-tenants',
            data: {}
          });
          
          if (result?.data) {
            this.tenantOptions = result.data.map(tenant => ({
              value: tenant.tenant_id,
              text: tenant.tenant_name || tenant.name || `商户(${tenant.tenant_id})`
            }));
          }
        } catch (e) {
          console.error('加载商户数据失败', e);
          uni.showToast({
            title: '加载商户列表失败',
            icon: 'none'
          });
        }
      },
      
      /**
       * 加载分类数据
       */
      async loadCategories() {
        try {
          const tenantId = this.isAdmin ? this.formData.tenant_id : this.currentTenantId;
          
          if (!tenantId) {
            this.categoryOptions = [];
            return;
          }
          
          let whereClause = { tenant_id: tenantId };
          
          const { result } = await uniCloud.callFunction({
            name: 'get-categories',
            data: { where: whereClause }
          });
          
          if (result?.data) {
            this.allCategories = result.data;
            
            this.categoryOptions = result.data.map(category => ({
              value: category._id,
              text: category.name || `未命名分类(${category._id})`
            }));
            
            if (this.categoryOptions.length === 0) {
              uni.showToast({
                title: '该商户暂无分类数据',
                icon: 'none'
              });
            }
          }
        } catch (e) {
          console.error('加载分类数据失败', e);
          uni.showToast({
            title: '加载分类列表失败',
            icon: 'none'
          });
        }
      },
      
      /**
       * 商户变更处理
       */
      onTenantChange(value) {
        this.formData.category_id = '';
        this.categoryOptions = [];
        
        if (value) {
          this.loadCategories();
        } else {
          uni.showToast({
            title: '请先选择商户',
            icon: 'none'
          });
        }
      },
      
      /**
       * 获取详情数据
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        });
        
        db.collection(dbCollectionName).doc(id).field("tenant_id,category_id,name,image,description,price,original_price,sort,is_hot,is_new,status,created_at,updated_at").get().then((res) => {
          const data = res.result.data[0];
          this.originData = {...data};
          
          if (!this.isAdmin && data.tenant_id !== this.currentTenantId) {
            uni.hideLoading();
            uni.showModal({
              content: '您没有权限编辑此菜品',
              showCancel: false,
              success: () => {
                uni.navigateBack();
              }
            });
            return;
          }
          
          if (data) {
            this.formData = data;
            
            // 如果存在图片，设置imageFiles用于预览
            if (data.image) {
              this.formData.imageFiles = [{
                name: '已上传图片',
                url: data.image,
                status: 'success'
              }];
            }
            
            if (this.isAdmin) {
              this.loadTenants();
              if (data.tenant_id) {
                this.loadCategories();
              }
            } else {
              this.loadCategories();
            }
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          });
        }).finally(() => {
          uni.hideLoading();
        });
      },
      
      /**
       * 提交表单
       */
      submit() {
        uni.showLoading({
          mask: true
        });
        
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res);
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading();
        });
      },
      
      /**
       * 提交表单数据
       */
      submitForm(value) {
        value.updated_at = Date.now();
        
        if (!this.isAdmin) {
          value.tenant_id = this.currentTenantId;
        }
        
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          });
          this.getOpenerEventChannel().emit('refreshData');
          setTimeout(() => uni.navigateBack(), 500);
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          });
        });
      },
      
      /**
       * 图片选择事件
       */
      onImageSelect(e) {
        console.log('选择文件：', e);
      },
      
      /**
       * 图片上传成功
       */
      onUploadSuccess(e) {
        console.log('上传成功：', e);
        if (e.tempFilePaths && e.tempFilePaths.length > 0) {
          this.formData.image = e.tempFilePaths[0];
        } else if (e.tempFiles && e.tempFiles.length > 0 && e.tempFiles[0].url) {
          this.formData.image = e.tempFiles[0].url;
        }
      },
      
      /**
       * 图片删除事件
       */
      onImageDelete(e) {
        console.log('删除文件：', e);
        this.formData.image = '';
      },
      
      /**
       * 开关类型的表单项数据绑定
       */
      binddata(name, value) {
        this.formData[name] = value;
      }
    }
  };
</script>

<style>
  .uni-button-group {
    margin-top: 30px;
    display: flex;
    justify-content: center;
  }
</style>
